package dell.day01;

import dell.JDBCUtils.JDBCUtils;
import org.junit.jupiter.api.Test;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

//针对Order表的通用查询
public class OrderForQuery {
    @Test
    public void testOrderForQuery(){
        String sql="select order_id orderId,order_name orderName," +
                "order_date orderDate from 'order' where orderId=? ";
        Order order=orderForQuery(sql,1);
        System.out.println(order);
    }
    public Order orderForQuery(String sql,Object...args){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();
            ps = conn.prepareStatement(sql);
            //填充占位符
            for (int i=0;i<args.length;i++){
                ps.setObject(i+1,args[i]);
            }
            //执行，获取结果集
            rs = ps.executeQuery();
            //获取结果集的元数据
            ResultSetMetaData rsmd = rs.getMetaData();
            //获取列数
            int columnCount = rsmd.getColumnCount();
            if (rs.next()){
                //当只有一个结果时
                Order order = new Order();
                for (int i=0;i<columnCount;i++){
                    //获取每个列的列值
                    //通过结果集
                    Object columnValue = rs.getObject(i + 1);
                    //列名是元数据，用来修饰结果集
                    //String columnName = rsmd.getColumnName(i + 1);
                    //获取每个列的别名
                    String columnLabel = rsmd.getColumnLabel(i + 1);
                    //通过反射，将对象columnName的属性赋值为指定的columnValue

                   Field field = Order.class.getDeclaredField(columnLabel);
                    //拿到属性名
                    field.setAccessible(true);
                    //保证私有的也可以访问
                    field.set(order,columnValue);
                    //给order当前的对象的属性设置为columnValue
                }
                return order;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.closeResource(conn,ps,rs);
        }
        return null;
    }

}
